package com.huiqiao.lesson4.service;

import com.huiqiao.lesson4.mapper.SysUserMapper;
import com.huiqiao.lesson4.pojo.SysUser;
import com.huiqiao.lesson4.utils.DBUtils;
import com.huiqiao.lesson4.utils.PasswordUtils;
import lombok.extern.log4j.Log4j2;

import java.util.List;

@Log4j2
public class SysUserService {

    private SysUserMapper userMapper = DBUtils.getUserMapper();

    /**
     * 注册用户，默认注册普通用户（01）
     * 密码转储密文存储
     */
    public void register(SysUser user) {
        SysUser oldUser = userMapper.selectUserByUserName(user.getUserName());
        if (oldUser != null) {
            throw new RuntimeException("注册失败，username已存在");
        }

        oldUser = userMapper.selectUserByPhone(user.getPhonenumber());
        if (oldUser != null) {
            throw new RuntimeException("注册失败，phonenumber已存在");
        }

        user.setUserType("01");
        user.setPassword(PasswordUtils.encrypt(user.getPassword()));
        int row = userMapper.insertUser(user);
        if (row > 0) {
            log.info("用户名：{} 注册成功", user.getUserName());
        } else {
            throw new RuntimeException("注册失败");
        }

    }

    /**
     *
     * @param username
     * @param password
     */
    public SysUser loginByUserName(String username, String password) {
        SysUser user = userMapper.selectUserByUserName(username);
        if (user == null) {
            throw new RuntimeException("登录失败, 用户不存在");
        }

        if (!PasswordUtils.verify(password, user.getPassword())) {
            throw new RuntimeException("登录失败, 密码校验不通过");
        }

        return user;
    }


}
